#!/bin/sh
set -xe
PICTURES_DIR="/usr/share/backgrounds"
DMENU_PROMPT="选择背景图："
XBGCLIP_CMD="xbgclip"

list_image_fullpaths() {
    find "${PICTURES_DIR}" -maxdepth 1 -type f \
        \( -iname "*.jpg"  -o -iname "*.jpeg" -o -iname "*.png"  \
        -o -iname "*.gif"  -o -iname "*.bmp"  -o -iname "*.webp" \
        -o -iname "*.svg" \)
}

selected_image=$(list_image_fullpaths | dmenu -i -p "${DMENU_PROMPT}" "$@")

if [ -z "$selected_image" ]; then
    exit 1
fi

# 使用printf避免添加换行符，移除回车字符
if command -v xclip >/dev/null 2>&1; then
    printf "%s" "$selected_image" | xclip -sel clip
fi

# 通过管道将路径传递给xbgclip
printf "%s" "$selected_image" | "${XBGCLIP_CMD}"
exit_code=$?

if command -v notify-send >/dev/null 2>&1; then
    if [ $exit_code -eq 0 ]; then
        notify-send "背景设置成功" "已将以下图片设为背景：\n$selected_image"
    else
        notify-send "背景设置失败" "设置图片时出现错误：\n$selected_image"
    fi
fi

exit $exit_code